package org.jash.sportnews2109.ui

import android.widget.SeekBar
import android.widget.Toast
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewmodel.initializer
import androidx.lifecycle.viewmodel.viewModelFactory
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.google.android.material.snackbar.Snackbar
import dagger.hilt.android.AndroidEntryPoint
import org.jash.common.adapter.CommonAdapter
import org.jash.common.mvvm.BaseFragment
import org.jash.sportnews2109.App
import org.jash.sportnews2109.BR
import org.jash.sportnews2109.R
import org.jash.sportnews2109.databinding.FragmentCategoryBinding
import org.jash.sportnews2109.entity.News
import org.jash.sportnews2109.entity.Page
import org.jash.sportnews2109.vm.CategoryViewModel

@Route(path = "/news/category")
@AndroidEntryPoint
class CategoryFragment : BaseFragment<FragmentCategoryBinding, CategoryViewModel>() {
    @Autowired
    @JvmField
    var id:Int = 0
    val size = 20
    var page = 1
    val adapter = CommonAdapter<News>(R.layout.news_item, BR.news)
    override fun initView() {
        binding.recycler.adapter = adapter
        binding.refresh.setOnRefreshListener {
            page = 1;
            viewModel.loadPage(id, page, size)
        }
        binding.refresh.setOnLoadMoreListener {
            viewModel.loadPage(id, ++page, size)
        }
    }

    override fun initData() {
        viewModel.pageLiveData.observe(this) {
            this.loaded(it)
        }
        ARouter.getInstance().inject(this)
        viewModel.loadPage(id, page, size)
    }
    fun loaded(page: Page<News>) {
        if (page.current == 1) {
            adapter.clear()
        }
        if (page.records.isEmpty()) {
            Toast.makeText(requireContext(), "没有更多的新闻!", Toast.LENGTH_SHORT).show()
        }
        adapter += page.records
        binding.refresh.closeHeaderOrFooter()
    }

    override fun error(throwable: Throwable) {
        super.error(throwable)
        binding.refresh.closeHeaderOrFooter()
    }
}